import tkinter as tk
from tkinter import ttk
import os   #检查图片路径是否存在
from PIL import Image, ImageTk   #控制图片大小
from link_SQLite import DatabaseManager
from link_start import LoginWindow
import datetime

#回复界面
class ReplyWindow:
    def __init__(self, master, post_title, post_content, post_time, db_manager, user_name, refresh_callback):
        self.master = master
        self.db_manager = db_manager
        self.post_title = post_title
        self.user_name = user_name

        self.refresh_callback = refresh_callback  # 保存回调函数

        self.top = tk.Toplevel(master)
        self.top.title("回复帖子")
        self.top.geometry("500x400")  # 设置窗口大小

        # 添加窗口关闭事件
        self.top.protocol("WM_DELETE_WINDOW", self.on_close)

        # 显示帖子标题
        title_label = tk.Label(self.top, text=f"标题: {post_title}", font=("Arial", 12))
        title_label.pack(pady=(10, 5))

        # 显示帖子内容
        content_label = tk.Label(self.top, text=f"内容: {post_content}", wraplength=480, justify="left")
        content_label.pack(pady=(5, 10))

        # 显示帖子时间
        time_label = tk.Label(self.top, text=f"时间: {post_time}", font=("Arial", 10))
        time_label.pack(pady=(5, 10))

        # 回复区域（最多显示5条回复）
        self.replies_frame = tk.Frame(self.top)
        self.replies_frame.pack(pady=(10, 10))
        self.load_and_display_replies()  # 加载并显示回复

        # 输入框
        self.reply_input = tk.Text(self.top, height=5, width=40)
        self.reply_input.pack(pady=(10, 10))

        # 发送按钮
        send_button = tk.Button(self.top, text="发送回复", command=self.send_reply)
        send_button.pack()

    def load_and_display_replies(self):
        # 从数据库获取回复
        replies = self.db_manager.fetch_replies_by_title(self.post_title)
        if replies:
            # 显示最新的5条回复
            self.display_replies(replies[-5:])  # 显示最新的5条回复


    def display_replies(self, replies):
        # 先清除现有的回复显示
        for widget in self.replies_frame.winfo_children():
            widget.destroy()
        
        # 显示最多5条回复，每条回复格式为“用户名：回复内容”
        for reply in replies:
            reply_text = f"{reply[0]}: {reply[2]}"  # 假设reply[0]是用户名，reply[2]是回复内容
            tk.Label(self.replies_frame, text=reply_text, wraplength=460).pack(anchor="w", pady=2)


    def send_reply(self):
        reply_content = self.reply_input.get("1.0", tk.END).strip()
        if reply_content:  # 确保不发送空回复
            # 假设我们有一个已经登录的用户名称，可以是一个类属性或通过其他方式获得
            current_user_name = self.user_name  # 需要替换成实际的用户名称获取方式

            # 添加保存到数据库的代码
            success = self.db_manager.add_reply_to_post(current_user_name, self.post_title, reply_content)
            if success:
                print("回复已成功添加到数据库")
            else:
                print("回复添加失败")

            # 然后重新加载和显示回复
            self.load_and_display_replies()
        self.reply_input.delete("1.0", tk.END)  # 发送后清空输入框

    def on_close(self):
        self.refresh_callback()  # 调用传入的回调函数来刷新主界面
        self.top.destroy()  # 关闭窗口




class ForumApp:
    def __init__(self, root):
        self.root = root
        self.root.title("论坛界面")
        self.root.geometry("700x800")  # 设置窗口大小

        self.current_page = 0
        self.posts_per_page = 4

         # 调用fetch_posts方法获取帖子信息
        self.posts_data = db_manager.fetch_posts()

        if self.posts_data is None:
            self.posts_data = []  # 确保posts_data至少是一个空列表，避免类型错误
            print("警告：未能从数据库加载帖子数据。")

        # 初始化界面组件
        self.setup_ui()

    def setup_ui(self):
        # 头部框架
        self.header_frame = tk.Frame(self.root, padx=10, pady=10)
        self.header_frame.pack(fill='x')

        self.title_label = tk.Label(self.header_frame, text="论坛标题", font=("Helvetica", 24))
        self.title_label.pack(side='left', expand=True, fill='both', padx=5)

        # 用户信息框架
        user_info_frame = tk.Frame(self.header_frame)
        user_info_frame.pack(side='right')

        # 用户头像
        avatar_path = ""  # 头像文件路径
        if avatar_path:
            avatar_image = ImageTk.PhotoImage(Image.open(avatar_path).resize((50, 50), Image.Resampling.LANCZOS))
            avatar_label = tk.Label(user_info_frame, image=avatar_image)
            avatar_label.image = avatar_image  # 防止图像被垃圾回收
            avatar_label.pack(side='left', padx=5)

        # 用户名标签
        self.user_info = tk.Label(user_info_frame, text="用户: 未登录", font=("Helvetica", 12))
        self.user_info.pack(side='right', padx=5)
        
        # 帖子列表框架
        self.posts_frame = tk.Frame(self.root, padx=10, pady=10)
        self.posts_frame.pack(fill='both', expand=True)

        self.display_posts()

        # 分页按钮框架
        self.pagination_frame = tk.Frame(self.root)
        self.pagination_frame.pack(fill='x', pady=10)

        self.first_page_button = tk.Button(self.pagination_frame, text="第一页", command=self.first_page)
        self.first_page_button.pack(side='left', padx=10, expand=True)

        self.prev_page_button = tk.Button(self.pagination_frame, text="上一页", command=self.prev_page)
        self.prev_page_button.pack(side='left', padx=10, expand=True)

        self.next_page_button = tk.Button(self.pagination_frame, text="下一页", command=self.next_page)
        self.next_page_button.pack(side='left', padx=10, expand=True)

        self.last_page_button = tk.Button(self.pagination_frame, text="最后一页", command=self.last_page)
        self.last_page_button.pack(side='left', padx=10, expand=True)

        # 输入框和发送按钮框架
        self.input_frame = tk.Frame(self.root)
        self.input_frame.pack(fill='x', pady=10)

        # 新增标题输入框
        self.title_input_box = tk.Entry(self.input_frame, width=20)
        self.title_input_box.pack(side='left', padx=10)

        self.input_box = tk.Text(self.input_frame, height=2, width=60)
        self.input_box.pack(side='left', padx=10, expand=True)

        self.send_button = tk.Button(self.input_frame, text="发送", command=self.send_post)
        self.send_button.pack(side='right', padx=10)

    def display_posts(self):
        # 清除posts_frame中的所有子组件
        for widget in self.posts_frame.winfo_children():
            widget.destroy()

        # 计算当前页显示的帖子范围
        start = self.current_page * self.posts_per_page
        end = start + self.posts_per_page

        # 遍历当前页的帖子数据
        for post in self.posts_data[start:end]:
            # 创建每个帖子的框架
            post_frame = tk.Frame(self.posts_frame, borderwidth=1, relief="solid")
            post_frame.pack(fill='x', padx=5, pady=5, expand=True)

            # 处理头像的加载和显示
            avatar_path = post[1]  # 从帖子数据中获取头像文件路径
            default_avatar_path = '头像1.png'  # 指定默认头像的路径

            # 检查头像文件路径是否有效，如果无效或文件不存在则使用默认头像
            if not avatar_path or not os.path.exists(avatar_path):
                avatar_path = default_avatar_path

            # 加载和显示头像
            try:
                avatar_image = ImageTk.PhotoImage(Image.open(avatar_path).resize((50, 50), Image.Resampling.LANCZOS))
                avatar_label = tk.Label(post_frame, image=avatar_image)
                avatar_label.image = avatar_image  # 防止图像被垃圾回收
                avatar_label.pack(side='left', padx=5)
            except Exception as e:
                print(f"无法加载图片 {avatar_path}: {e}")

            # 显示帖子的标题
            title_label = tk.Label(post_frame, text=post[3], font=("font.BOLD", 12, "bold"))
            title_label.pack(side='top', padx=5)

            # 显示帖子的内容
            content_label = tk.Label(post_frame, text=post[4], font=("font.BOLD", 10), wraplength=500)
            content_label.pack(side='top', padx=5)

            # 显示帖子的额外信息
            info_label = tk.Label(post_frame, text=f"发布人: {post[2]} |发布时间: {post[5]} | 回复: {post[6]} | 点赞: {post[7]}", font=("font.BOLD", 10))
            info_label.pack(side='top', padx=5)

            # 添加回复和点赞按钮
            reply_button = tk.Button(post_frame, text="回复", command=lambda post=post: self.reply_to_post(post))
            reply_button.pack(side='right', padx=10)

            like_button = tk.Button(post_frame, text="点赞", command=lambda post=post: self.like_post(post))
            like_button.pack(side='right', padx=10)

    #封装登录功能
    def ensure_login(self):
        if not hasattr(self, 'current_user') or not self.current_user:
            login_window = tk.Toplevel(self.root)
            login_app = LoginWindow(login_window)
            login_window.grab_set()  # 让登录窗口获得所有的焦点直到被关闭

            # 等待登录窗口关闭
            self.root.wait_window(login_window)

            # 检查登录是否成功
            if login_app.login_success:
                self.current_user = login_app.username
                self.user_info.config(text=f"用户: {self.current_user}")
            else:
                return False  # 登录失败或未登录
        return True

    
    def refresh_posts(self):
        try:
            self.posts_data = db_manager.fetch_posts()
            if not self.posts_data:
                self.posts_data = []  # 如果没有帖子数据，确保它是一个空列表
                print("警告：未能从数据库加载帖子数据。")
            self.display_posts()  # 调用display_posts方法来更新帖子显示
        except Exception as e:
            print(f"错误：无法从数据库加载帖子数据。{e}")

    #发送逻辑
    def send_post(self):
        if self.ensure_login():
            #获取标题
            post_title = self.title_input_box.get()
            #获取内容
            post_content = self.input_box.get("1.0", "end-1c")
            #获取时间
            post_time = datetime.datetime.now()
            db_manager.add_post(self.current_user, post_title, post_content, post_time)
            self.title_input_box.delete(0, 'end')
            self.input_box.delete("1.0", "end")
            self.refresh_posts()


    #下面4个是按钮调用函数
    def first_page(self):
        self.current_page = 0
        self.display_posts()

    def prev_page(self):
        if self.current_page > 0:
            self.current_page -= 1
            self.display_posts()

    def next_page(self):
        if (self.current_page + 1) * self.posts_per_page < len(self.posts_data):
            self.current_page += 1
            self.display_posts()

    def last_page(self):
        self.current_page = len(self.posts_data) // self.posts_per_page
        if len(self.posts_data) % self.posts_per_page == 0:
            self.current_page -= 1
        self.display_posts()

    #回复
    def reply_to_post(self, post):
        if self.ensure_login():
            # 从post元组中获取帖子的标题、内容和时间
            post_title, post_content, post_time = post[3], post[4], post[5]
            # 创建回复窗口并传递db_manager实例
            ReplyWindow(self.root, post_title, post_content, post_time, db_manager,self.current_user,self.refresh_posts)


    #点赞
    def like_post(self, post):
        if self.ensure_login():
            SKR = db_manager.check_post_existence(post[3],self.current_user)
            print("返回值找到是0，没找到是1:",SKR) #因为在link里面打印了，所以不需要
            SKR_ADD = db_manager.add_or_delete_post(self.current_user,post[3],SKR)
        self.refresh_posts()

if __name__ == "__main__":
    # 创建DatabaseManager实例
    db_manager = DatabaseManager()

    
    root = tk.Tk()
    app = ForumApp(root)
    root.mainloop()
